﻿using ALEXBlog.Entity;
using ALEXBlog.IRepository.Base;
using ALEXBlog.Repository.Sugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace ALEXBlog.Repository
{
    public class BaseRepository : IBaseRepository
    {
        DbContext dbContext;
        SqlSugarClient dbClient;
        SimpleClient<UsersModel> entityDb;

        public DbContext DbContext { get => dbContext; set => dbContext = value; }
        public SqlSugarClient DbClient { get => dbClient; set => dbClient = value; }
        public SimpleClient<UsersModel> DbEntity { get => entityDb; set => entityDb = value; }

        public BaseRepository()
        {
            DbContext.Init(BaseDbConfig.ConnectionString);
            dbContext = DbContext.GetDbContext();
            dbClient = dbContext.dbClient;
            entityDb = dbContext.GetEntityDB<UsersModel>();
        }

        public Task<int> AddAsync<TEntity>(params TEntity[] models) where TEntity : class, new()
        {
            return dbClient.Insertable(models).ExecuteCommandAsync();
        }

        public Task<int> RemoveAsync<TEntity>(params TEntity[] models) where TEntity : class, new()
        {
            return dbClient.Deleteable<TEntity>(models).ExecuteCommandAsync();
        }

        public Task<int> RemoveAsync<TEntity>(object id) where TEntity : class, new()
        {
            return dbClient.Deleteable<TEntity>(primaryKeyValue: id).ExecuteCommandAsync();
        }

        public Task<int> RemoveAsync<TEntity>(params object[] ids) where TEntity : class, new()
        {
            return dbClient.Deleteable<TEntity>(pkValue: new List<dynamic>(ids)).ExecuteCommandAsync();
        }

        public Task<int> UpdateAsync<TEntity>(params TEntity[] models) where TEntity : class, new()
        {
            return dbClient.Updateable(models).ExecuteCommandAsync();
        }

        public Task<TEntity> FindAsync<TEntity>(Expression<Func<TEntity, bool>> whereExpression) where TEntity : class, new()
        {
            return dbClient.Queryable<TEntity>().FirstAsync(whereExpression);
        }

        public Task<List<TEntity>> QueryAsync<TEntity>() where TEntity : class, new()
        {
            return dbClient.Queryable<TEntity>().ToListAsync();
        }

        public Task<List<TEntity>> QueryAsync<TEntity>(Expression<Func<TEntity, bool>> whereExpression) where TEntity : class, new()
        {
            return dbClient.Queryable<TEntity>().Where(whereExpression).ToListAsync();
        }

        public Task<List<TEntity>> QueryAsync<TEntity>(int pageIndex, int pageSize, Expression<Func<TEntity, bool>> whereExpression) where TEntity : class, new()
        {
            return dbClient.Queryable<TEntity>().Where(whereExpression).ToPageListAsync(pageIndex, pageSize);
        }
    }
}
